package com.atguigu.practice;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket=null;
    private String serverIP;
    private int serverPort;
    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        //这里让系统分配一个空闲的端口
        socket=new DatagramSocket();
        this.serverIP=serverIP;
        this.serverPort=serverPort;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }

    public void start() throws IOException {
        while(true){
            //1.从控制台读取用户输入的内容
            Scanner scanner=new Scanner(System.in);
            String request=scanner.next();
            //2.构造一个UDP请求，发给服务器
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length
            , InetAddress.getByName(this.serverIP),this.serverPort);
            socket.send(requestPacket);
            //3.从服务器读取UDP响应数据，并解析
            DatagramPacket responsePacket=new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            //4.把服务器的响应显示到控制台上
            System.out.println(response);
        }
    }
}
